// pages/Goods/GoodsDes/index.js
const app = getApp()
var common = require('../../../../public.js')
const config = require('../../../config.js')
Page({
    /**
     *  页面的初始数据
     */
    data: {
        isOverShare: true,  //全局分享标识请勿删除
        isFyApp: config.isFyApp,
        itemId: '', //商品id
        title: '', //页面title
        shopData: [], //店铺数据
        Des: {}, //商品详情
        storeCouponsList: [
            // {exceedMoney:100,discountsMoney:10},
            // {exceedMoney:100,discountsMoney:10},
        ], //店铺优惠券列表
        postMethodStr: '',
        storeId: '', //店铺Id
        attenyes: false, //店铺已关注
        attenno: true, //店铺关注
        property: false, //商品属性
        isVip: false,
        showVip: false,
        inviteCode: '',
        inputShowed: false,
        chackStep: 1,
        inviter: '', //邀请人信息
        code: '', // 用户vipcode
        commnet: '', // 评论对象
        commentType: '0', //评论类型 0=前两条  1=全部
        showComment: false,
        commentPlaceHolder: '我来说几句',
        commentValue: '',
        showGoodsParam: false, // 商品参数
        showIndemnity: false, // 消保面板
        showStoreCoupons: false, //店铺优惠券面板
        inputFocus: false,
        addCartPopup: false,
        goodsCount: 1,
        image: null,
        sellPoint: null,
        isLoadingBusy: false,
        favoriteGoodsFlag: false,
        qrcodeid: "",
        commnetTotalNums: "",
        storeId: ''
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (opt) {
        var that = this
        //获取胶囊位置
        console.log(opt, "ceshishsi666666666666666666666")
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        var windowHeight = wx.getSystemInfoSync().windowHeight
        var windowWidth = wx.getSystemInfoSync().windowWidth
        this.setData({
            scroll_height: windowHeight * 750 / windowWidth - 200
        })
        if (opt.q) {
            let scan_url = decodeURIComponent(opt.q);
            let video_id = scan_url.match(/\d+/) //提取链接中的数字，也就是链接中的参数id，/\d+/ 为正则表达式
            this.setData({
                qrcodeid: video_id[0]
            })
            this.setData({
                isLoadingBusy: true
            })
            var that = this;
            that.setData({
                itemId: this.data.qrcodeid,
                title: "飞羊精选",
                isVip: opt.isVip ? true : false,
                image: opt.image ? opt.image : null,
                sellPoint: opt.sellPoint ? opt.sellPoint : null
            })
            wx.setNavigationBarTitle({
                title: that.data.title, //页面标题为路由参数
            })
            common.getLocalUserInfo(function (success, data) {
                if (success) {
                    that.setData({
                        userInfo: data.user,
                        token: data.token,
                        openid: data.openid
                        // itemId: that.options.id,
                    })

                    that.getDataDes() //查询商品详情信息
                    that.getartists() //判断是否是守艺人
                    that.getgoodsArrtention() //判断商品是否收藏
                    that.getGoodsCommentList() // 获取商品评论
                } else {
                    that.getDataDes() //查询商品详情信息
                    that.getartists() //判断是否是守艺人
                    that.getgoodsArrtention() //判断商品是否收藏
                    that.getGoodsCommentList() // 获取商品评论
                }
            }, true)
            return
        } else {
            console.log(opt)
            this.setData({
                isLoadingBusy: true
            })
            var that = this;
            that.setData({
                itemId: opt.id,
                // itemId:19205,
                title: opt.name,
                isVip: opt.isVip ? true : false,
                image: opt.image ? opt.image : null,
                sellPoint: opt.sellPoint ? opt.sellPoint : null
            })
            wx.setNavigationBarTitle({
                title: that.data.title, //页面标题为路由参数
            })
            common.getLocalUserInfo(function (success, data) {
                if (success) {
                    that.setData({
                        userInfo: data.user,
                        token: data.token,
                        openid: data.openid
                        // itemId: that.options.id,
                    })
                    that.getDataDes() //查询商品详情信息
                    that.getGoodsCommentList() // 获取商品评论
                    that.getartists() //判断是否是守艺人
                    that.getgoodsArrtention() //判断商品是否收藏

                }

            }, true)

        }


    },
    //判断是否是守艺人
    getartists: function () {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id
        };
        common.post("/isPromoter", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    code: res.data || ''
                })
            }
        })
    },
    toStore() { //跳转店铺
        const storeType = this.data.shopData.storeType
        console.log(this.data.shopData, "toStore")
        common.gotoStore(this.data.shopData)
    },
    focusInput() {
        this.setData({
            inputShowed: true
        })
    },
    changeCode(e) {
        this.setData({
            inviteCode: e.detail.value
        })
    },
    getInviteCode() {
        let that = this
        if (that.data.inviteCode.length < 6) {
            common.showToast('请填写正确的邀请码')
            return false
        }
        let tempJson = {
            inviteCode: that.data.inviteCode,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.post("/getPromoterInfo", tempJson, function (res) {
            if (res.status == 200) {
                that.setData({
                    inviter: res.data,
                    chackStep: 2
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    onClose() {
        this.setData({
            showVip: false,
            chackStep: 1,
            inviteCode: ""
        })
    },
    // 店铺优惠券列表
    getStoreCoupons(refresh = true) {
        const that = this
        if (refresh) {
            this.data.canLoad = true
        }
        if (that.data.canLoad) {  //可以加载
            if (!refresh && this.data.isLoadingBusy) {
                return
            }
            this.setData({
                isLoadingBusy: true
            })
            const params = {
                storeId: that.data.storeId,
                pageNum: refresh ? 1 : that.data.pageNum + 1,
                status: 4
            }
            common.post("/discountCoupon/showDiscoutCouponList", params, function (res) {
                if (res.status === 200) {
                    that.data.pageNum = params.pageNum
                    if (res.data.result_list != '' || res.data.result_list.length != 0) {
                        that.setData({
                            storeCouponsList: [...that.data.storeCouponsList, ...res.data.result_list],
                        })
                    } else {
                        if (that.data.pageNum == 1) {
                            that.setData({
                                storeCouponsList: []
                            })
                            return
                        }
                        that.setData({
                            canLoad: false,
                        })
                    }

                }
            }, function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
        }

    },
    //查看是否关注店铺
    // getshopArrtention: function () {
    //   var that = this
    //   var tempJson = {
    //     token: that.data.token,
    //     userId: that.data.userInfo.id,
    //     storeId: that.data.storeId
    //   };
    //   common.post("/store/favo/collected", tempJson, function (res) {
    //     if (res.status == 200) {
    //       that.setData({
    //         attenyes: true,
    //         attenno: false
    //       })
    //     } else {
    //       that.setData({
    //         attenyes: false,
    //         attenno: true
    //       })
    //     }
    //   });
    // },
    //查询是否收藏商品状态
    getgoodsArrtention: function () {
        const that = this
        const tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            itemId: that.data.itemId
        }
        common.post("/item/favo/collected", tempJson, function (res) {
            if (res.status == 200) {
                that.setData({
                    favoriteGoodsFlag: true
                })
            } else {
                that.setData({
                    favoriteGoodsFlag: false
                })
            }
        })
    },
    //关注该店铺
    // attention_no: function () {
    //   var that = this
    //   var tempJson = {
    //     token: that.data.token,
    //     userId: that.data.userInfo.id,
    //     storeId: that.data.storeId
    //   };
    //   common.wxRequest("/store/favo/add", "get", tempJson, 'application/json', function (res) {
    //     if (res.status == 200) {
    //       that.setData({
    //         attenyes: true,
    //         attenno: false
    //       })
    //       wx.showToast({
    //         title: '已关注',
    //         icon: 'none'
    //       })
    //     } else {
    //       wx.showToast({
    //         title: '关注失败',
    //         icon: 'none'
    //       })
    //     }
    //   });
    // },
    //取消收藏该商品
    favoriteGoods(collect) {
        const that = this
        const tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            itemId: that.data.itemId
        }
        const url = collect ? '/item/favo/add' : '/item/favo/delete'
        common.post(url, tempJson, function (res) {
            if (res.status == 200) {
                that.setData({
                    favoriteGoodsFlag: collect
                })
                common.showToast(collect ? '已收藏' : '已取消收藏')
            } else {
                common.showToast(collect ? '收藏失败' : '取消失败')
            }
        })
    },
    //取消关注该店铺
    attention_yes: function () {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.wxRequest("/store/favo/delete", "get", tempJson, 'application/json', function (res) {
            if (res.status == 200) {
                that.setData({
                    attenyes: false,
                    attenno: true
                })
                wx.showToast({
                    title: '已取消关注',
                    icon: 'none'
                })
            } else {
                wx.showToast({
                    title: '取消失败',
                    icon: 'none'
                })
            }
        });
    },
    //查询商品详情信息
    getDataDes: function () {
        var that = this
        var tempJson = {
            itemId: that.data.itemId,
            // itemId:8102
            // itemId:8313
        }
        common.post("/item/info", tempJson, function (res) {
            if (res.status === 200) {
                //itemAttrList没有数据隐藏商品属性模块 有数据显示遍历
                if (res.data.itemAttrList.length == 0) {
                    that.setData({
                        property: true
                    })
                } else {
                    that.setData({
                        property: false,
                        itemAttrList: res.data.itemAttrList,
                        image: res.data.image,
                        title: res.data.title
                    })
                }
                // var newResData = JSON.parse( res.data.itemDesc);
                const richText = res.data.itemDesc ? res.data.itemDesc.replace(/\<img/gi, "<img mode='aspectFill' ") : ''
                // const richText =  res.data.itemDesc.replace(/<img/gi, "<img class='richImg'style='max-width:100%;height:auto;display:block;margin:10px 0;'");
                // var jsonDa = JSON.stringify(res.data.itemDesc).replace(/<img/gi, "<img class='richImg' style='width:375rpx!important;height:auto!important;max-height:100%;' max-width:100%!important");
                //遍历得到的数据，给img添加CSS和style
                // var newResData = JSON.parse(jsonDa);
                // var jsonDa = JSON.stringify(res.data.itemDesc).replace(/<img style=' /gi, "<img class='richImg' style='width:375rpx !important; height:auto !important; max-height:100%; max-width:375rpx!important' ")
                //var newResData = JSON.parse(jsonDa);
                // console.log(newResData,"newResDatanewResDatanewResData")
                let str = richText.replace(/<img[^>]*>/gi, function (match, capture) {
                    return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:100%;height:auto; width:100%";height:100%') // 替换style
                    //  match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:100%;height:auto; width:100%";height:100%') // 替换style      
                })
                console.log(str,"ssssssssssssssssssssssss")
                that.setData({
                    Des: res.data,
                    title: res.data.title,
                    storeId: res.data.storeId,
                    goodsInformation: str,
                    sellPoint: res.data.sellPoint
                }, function () {
                    that.getShopDes(); //店铺信息
                    that.getPostMethod(); // 获取配送方式
                    // that.getshopArrtention(); //是否关注店铺
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoadingBusy: false
            })
        })
    },
    //查询店铺详情信息
    getShopDes: function () {
        const that = this
        const tempJson = {
            storeId: that.data.storeId
        }
        common.post("/store/info", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    shopData: res.data,
                    storeId: res.data.id
                }, function () {
                    that.getStoreCoupons(true)
                })
            }
        })
    },
    receiveStoreConpons(e) {
        let that = this
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }
        common.post("/discountCoupon/getShopCoupon", tempJson, function (res) {
            if (res.status == 200) {
                wx.showToast({
                    title: '领取成功',
                    icon: "none"
                })
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '领取失败',
                    icon: "none"
                })
            }
        })
    },
    // 点击购买vip商品
    buyVipGoods() {
        console.log('aaaaa--');
        let that = this
        app.globalData.cardId = '';
        app.globalData.discount = 1
        app.globalData.productprice = ''

        wx.navigateTo({
            url: '/packageA/pages/Goods/Commit/index?itemId=' + that.data.Des.id + '&storeId=' + that.data.storeId + '&invitationCode=' + that.data.inviteCode,
        })
    },
    purchase() {
        var that = this
        console.log('vip1', that.data.isVip)
        console.log('vip2', that.data.code)
        if (that.data.isVip && that.data.code == '') { // 是vip商品且用户不是手艺人
            that.setData({
                showVip: true
            })
        } else {
            console.log('这里-00------');
            app.globalData.cardId = '';
            app.globalData.discount = 1
            app.globalData.productprice = ''
            wx.navigateTo({
                url: '../Commit/index?itemId=' + that.data.Des.id + '&storeId=' + that.data.storeId,
            })
        }
    },
    goBack() {
        wx.navigateBack({
            url: '../../index/index'
        })
    },
    comeInClick() {
        if (this.data.qrcodeid) {
            wx.redirectTo({
                url: '/pages/index/index',
            })
            return
        }
        const pages = getCurrentPages()
        wx.navigateBack({
            delta: pages.length
        })

    },
    getPostMethod() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId
        };
        common.post("/store/getPostTypeNew", tempJson, function (res) {
            if (res.status === 200) {
                let postType = []
                res.data.map(item => {
                    postType.push(item.dname)
                })
                that.setData({
                    postMethodStr: postType.join(' | ')
                })
            }
        })
    },
    gotoCart() {
        wx.showToast({
            title: '功能升级中，即将开放',
            icon: 'none'
        })
        // wx.redirectTo({
        //   url: '/packageB/pages/ShoppingCart/index',
        // })
    },
    collectionAction() {
        this.favoriteGoods(true)
        // if (this.data.favoriteGoodsFlag) {
        //   this.favoriteGoods(false)
        // } else {
        //   this.favoriteGoods(true)
        // }
    },
    collectionAction_qv() {
        this.favoriteGoods(false)
    },
    //获取评论列表
    getGoodsCommentList() {
        var that = this
        var tempJson = {
            itemId: that.data.itemId,
            pageNum: '',
            type: that.data.commentType, //0标识取前2条   1全部数据
            userId: that.data.userInfo.id
        };
        common.post("/comment/getItemCommentlist", tempJson, function (res) {
            console.log(res)
            that.setData({
                commnet: res.data,
                commnetTotalNums: res.data.commnetTotalNums
            })
        })
    },
    //点击回复
    clickRely(e) {
        let {
            item
        } = e.currentTarget.dataset
        let that = this
        console.log(item)
        this.setData({
            showComment: true,
            commentPlaceHolder: '@' + item.alias + ':',
            commentId: item.id
        }, _ => {
            setTimeout(function () {
                that.setData({
                    inputFocus: true
                })
            }, 500)
        })
    },
    //输入评论
    changeCommnet(e) {
        console.log(e)
        let {
            value
        } = e.detail
        this.setData({
            commentValue: value
        })
    },
    saveComment() {
        if (this.data.commentValue === null || this.data.commentValue.length === 0) {
            wx.showToast({
                icon: 'none',
                title: '您没有输入任何文字',
            })
            return
        }
        const that = this
        wx.cloud.callFunction({
            name: 'ContentCheck',
            data: {
                txt: that.data.commentValue
            },
            success(res) {
                if (res.result.errCode == 87014) {
                    console.log(res.errCode)
                    wx.showToast({
                        icon: 'none',
                        title: '文字违规，请重新输入',
                    })
                } else {
                    // 合规
                    let tempJson = {
                        userId: that.data.userInfo.id,
                        token: that.data.token,
                        commentId: that.data.commentId,
                        content: that.data.commentValue
                    }
                    common.post('/comment/saveItemCommentChat', tempJson, function (res) {
                        console.log(res)
                        if (res.status == 200) {
                            that.onCommentClose()
                            that.getGoodsCommentList()
                            wx.showToast({
                                title: '评论成功',
                            })
                        } else {
                            common.showRequestErrMsg(res)
                        }
                    })
                }
            },
            fail(err) {
                wx.showToast({
                    icon: 'none',
                    title: '文字违规，请重新输入',
                })
            }
        })
    },
    OpenStoreCouponos() {
        this.setData({
            showStoreCoupons: true
        })
    },
    onStoreCouponosClose() {
        this.setData({
            showStoreCoupons: false
        })
    },
    OpenGoodsParam() {
        this.setData({
            showGoodsParam: true
        })
    },
    closeGoodsParam() {
        this.setData({
            showGoodsParam: false
        })
    },
    OpenIndemnity() {
        this.setData({
            showIndemnity: true
        })
    },
    closeIndemnity() {
        this.setData({
            showIndemnity: false
        })
    },
    onCommentClose() { // 关闭模态框
        console.log('666')
        this.setData({
            commentId: ' ',
            commentValue: ' ',
            showComment: false,
        })
    },
    commentPraise(e) { //点赞
        console.log(e.currentTarget.dataset)
        let {
            id
        } = e.currentTarget.dataset
        let that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            commnetId: id
        }
        common.post('/comment/saveCommentPraise', tempJson, function (res) {
            console.log(res)
            if (res.status == 200) {
                that.getGoodsCommentList()
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    // 列表触底
    loadMore() {
        this.getStoreCoupons(false)
    },
    //取消点赞
    cancleCommentPraise(id) {
        let that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            commnetId: id
        }
        common.post("/comment/cancleCommentPraise", tempJson, function (res) {
            if (res.status === 200) {
                that.getGoodsCommentList()
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    //获取全部列表
    getAllComment() {
           app.globalData.cardId = '';
        wx.navigateTo({
            url: '/packageA/pages/Goods/Comment/index?itemId=' + this.data.itemId,
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: this.data.title,
            path: '/packageA/pages/Goods/GoodsDes/index?id=' + this.data.itemId,
            // imageUrl: '/images/home.png',
            success: (res) => {
                // 分享成功
            },
            fail: (res) => {
                // 分享失败
            }
        }
    },
    addCart() { },
    showAddCart() {
        wx.showToast({
            icon: 'none',
            title: '功能升级中，即将开放',
        })
        // this.setData({
        //   addCartPopup: true
        // })
    },
    closeAddCart() {
        this.setData({
            addCartPopup: false
        })
    },
    onNumChange(e) {
        const count = e.currentTarget.detail
        this.setData({
            goodsCount: count
        })
    },
    submitAddCart() {
        const that = this
        const num = this.data.goodsCount
        const itemId = this.data.itemId
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId,
            num
        }
        common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.closeAddCart()
                wx.showToast({
                    title: '添加成功!',
                })
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopData.mobile,
            fail: function (res) { }
        })
    },
    onShow() {
        this.setData({
            stopmuic: false
        })
    },
})